<?php

namespace App\Models;

use DB;
class Shop extends BaseModel
{
    protected $table = "shop";

    protected $redisTable = "shop";

    protected $rules = [
        'shop_name' => 'required|between:1,15|unique:shop,shop_name',
        'boss_name' => 'required|between:1,5',
        'shop_phone' => 'required|regex:/^1[3456789]{1}\d{9}$/',
        'province_id' => 'required|digits:6',
        'city_id' => 'digits:6',
        'area_id' => 'required|digits:6',
        'area_info' => 'required',
        'address' => 'required|between:1,50',
    ];

    protected $message = [
        'shop_name.required' => '店铺名称必须填写',
        'shop_name.between' => '店铺名称不能超过15个字',
        'shop_name.unique' => '该店铺名称已存在，请重新输入',
        'boss_name.required' => '经营者姓名称必须填写',
        'boss_name.between' => '经营者姓名不能超过5个字',
        'shop_phone.required' => '联系方式必须填写',
        'shop_phone.regex' => '请输入正确的手机号',
        'province_id.required' => '请选择所属省份',
        'province_id.digits' => '非法数据',
        'city_id.digits' => '非法数据',
        'area_id.required' => '请选择所属区域',
        'area_id.digits' => '非法数据',
        'area_info.required' => '请选择所属地区',
        'address.required' => '店铺详细地址必须填写',
        'address.between' => '店铺详细地址不能超过50个字',
    ];

    protected $accountRule = [
        'username' => 'required|between:3,20|unique:shop,username',
        'password' => 'required|between:6,30',
        'confirm_password' => 'required|same:password'
    ];

    protected $accountMsg = [
        'username.required' => '账号必须填写',
        'username.between' => '账号长度不合法，应为3-20位字符',
        'username.unique' => '此账号已存在，请重新输入',
        'password.required' => '密码必须填写',
        'password.between' => '密码长度不合法，应为6-30位字符',
        'confirm_password.required' => '确认密码必填',
        'confirm_password.same' => '两次密码不一致',
    ];

    public function shopAccount()
    {
        return $this->hasOne('App\Models\ShopAccount','shop_id','id');
    }

    public function saoPay()
    {
        return $this->hasOne('App\Models\SaoPay', 'shop_id', 'id');
    }

    public function getShopList()
    {
        $keyword = request('keyword');
        if(plat_identify() == 'admin') {
            if (is_administrator()) {
                $where = [];
            } else {
                $where['admin_id'] = plat_admin_id();
            }
        } else {
            $where['id'] = session('account')['shop_id'];
        }

        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['shop_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $fields = 'id,admin_id,username,shop_name,boss_name,total_goods_num,total_water_bill_num,deposit,start_time,end_time,status';
        $rows = $this->_getPageList($where,$fields,['id' => 'asc'],10,5);
        $txtStr['status'] = [1 => '开启', -1 => '关闭', 0 => '审核', 2 => '欠费'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }

    public function getOwnShopList()
    {
        $keyword = request('keyword');
        $where['admin_id'] = plat_admin_id();
        if ($keyword) {
            if (is_numeric($keyword)) {
                $where['id'] = $keyword;
            } else {
                $where['shop_name'] = ['like', '%' . $keyword . '%'];
            }
        }
        $rows = $this->_getPageList($where);
        $txtStr['status'] = [1 => '开启', -1 => '关闭', 0 => '审核', 2 => '欠费'];
        $rows['data'] = int_to_string($rows['data'], $txtStr);
        return $rows;
    }


    public function addOrUpdate()
    {
        $data['shop_name'] = trim(request('shop_name'));
        $data['boss_name'] = trim(request('boss_name'));
        $data['shop_phone'] = trim(request('shop_phone'));
        $data['province_id'] = request('province');
        $data['area_id'] = request('area');
        $data['area_info'] = request('area_info');
        $data['address'] = trim(request('address'));
        $data['shop_position'] = trim(request('shop_position',''));
        $data['addtime'] = time();
        if (request('id')) {
            $data['id'] = trim(request('id'));
            $this->rules['shop_name'] .= ',' . $data['id'] . ',id,admin_id,' . plat_admin_id(); //唯一字段验证,在更新时排除当前id
        } else {
            $data['admin_id'] = intval(request('admin_id')) ? intval(request('admin_id')) : plat_admin_id();
            $data['status'] = 1; //初期使用免费开放，后期更改为0
            $data['start_time'] = time(); //初期使用免费开放，后期更改为0
//            $data['end_time'] = strtotime(date("y-m-d", strtotime("+3 days"))); //初期使用免费开放8天，后期更改为0
            $data['end_time'] = 1924790400; //不限期
            $this->rules['shop_name'] .= ',' . NULL . ',' . NULL . ',admin_id,' . $data['admin_id'];//唯一字段验证,在新增时锁定验证范围在当前商户下
        }
        if (request('city')) {
            $data['city_id'] = trim(request('city'));
        }
        // 判断是否是快捷开店
        if(request('type') == 'simple'){
            $data['username'] = request('username');
            $shop = DB::table('shop')
                ->where('username', $data['username'])
                ->orWhere('shop_name', $data['shop_name'])
                ->orWhere('shop_phone', $data['shop_phone'])
                ->first();
            if($shop){
                $this->error = '店铺名称/店铺账号/联系方式已存在';
                return false;
            }
            $password = '123456'; //初始密码默认为123456
            $data['password'] = $password;
            $data['confirm_password'] = $password;
            if(!$this->_validate($data, 'accountRule', 'accountMsg')){
                return false;
            }
            unset($data['confirm_password']);

            if(request('captcha')){
                $captcha = request('captcha');
                $smsLog = new SmsLog();
                $res = $smsLog->checkSmsCaptcha($data['shop_phone'], $captcha, 3);
                if (!$res['status']) {
                    $this->error = $res['msg'];
                    return false;
                }
            } else {
                $this->error = '请输入短信验证码';
                return false;
            }
            $data['admin_id'] = request('aid', 2); //快捷开店先默认admin_id = 2
            $data['password'] = md5($password);
        }
        if (!$this->_validate($data)) {
            return false;
        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存失败!';
            return false;
        }
        $id = isset($data['id']) ? $data['id'] : $res;
        $this->_redisGenerate($id);
        //记录行为
//        action_log('update_shop', 'shop', $id);
        return $res;
    }

    public function setting()
    {
        $data['id'] = trim(request('id'));
        $data['pic_num'] = request('imgs') ? count(request('imgs')) : 0;
        $data['contact'] = trim(request('contact'));
        $data['cd_contact'] = trim(request('cd_contact'));
        $data['work_time'] = trim(request('work_time'));
        $data['send_area_radius'] = trim(request('send_area_radius',0));
        $data['send_area'] = trim(request('send_area'));
        $data['notice'] = trim(request('notice', ''));
        $data['bill_notice'] = request('bill_notice');
        $data['offline_pay'] = request('offline_pay');
        $data['online_pay'] = request('online_pay');// 默认开启微信支付
        $data['cui_dan'] = request('cui_dan');
        $data['buy_min'] = request('buy_min');
        $data['buy_max'] = request('buy_max');
        $data['send_mode'] = request('send_mode');
        $data['withdraw_min'] = request('withdraw_min');
        $data['address'] = trim(request('address'));

        $data['province_id'] = request('province');
        $data['area_id'] = request('area');
        $data['area_info'] = request('area_info');
        if (request('city')) {
            $data['city_id'] = trim(request('city'));
        }
        if(request('shop_position')) {
            $data['shop_position'] = trim(request('shop_position'));
        }

        if($data['buy_min'] > $data['buy_max']) {
            $this->error = '最大购买上限不得小于最小购买上限！';
            return false;
        }

//        if (request('pics')) {
        $fields = request('imgs');
            $picture = new Picture();
            $picture->config['savePath'] = '/uploads/shops/imgs/';
            $picture->config['cutSize'] = '400,150';
            $picture->config['cut_Mini_Size'] = '';
            $picture->config['maxNum'] = 1;
            $res = $picture->upload($data['id'],'',$fields);
            if (!$res) {
                $this->error = $picture->getError();
                return false;
            }
//        }
//        if (request('logo')) {
            $fields = request('logo');
            $picture->config['savePath'] = '/uploads/logos/imgs/';
            $picture->config['cutSize'] = '80,80';
            $res = $picture->upload($data['id'], '', $fields);
            if (!$res) {
                $this->error = $picture->getError();
                return false;
            }
//        }
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存信息失败！';
            return false;
        }
        $this->_redisGenerate($data['id']);
        return $res;
    }

    public function saveSliders()
    {
        $data['id'] = trim(request('id'));
        $data['slide_num'] = count(request('pics'));
        $res = $this->_save($data);
        if (!$res) {
            $this->error = '保存失败！';
            return false;
        }
        $picture = new Picture();
        $picture->config['savePath'] = '/uploads/sliders/imgs/';
        $picture->config['cutSize'] = '420,150';
        $picture->config['cut_Mini_Size'] = '';
        $res = $picture->upload($data['id']);
        if (!$res) {
            $this->error = $picture->getError();
            return false;
        }
        $this->_redisGenerate($data['id']);
        return $res;
    }

    public function _redisGenerate($sid)
    {
        $table = $this->redisTable;
        $key = $sid;
        $this->redis->hdel($table, $key);
    }


    public function _redisGetOneBySid($sid)
    {
        $table = $this->redisTable;
        $key = $sid;
        if ($this->redis->hexists($table, $key)) {
            $res = $this->redis->hmget($table, $key);
            if ($res) {
                return unserialize($res[0]);
            }
        }
        $res = $this->_getOneById($sid);
        if ($res) {
            $res = $res->toArray();
            $this->redis->hmset($table, [$key => serialize($res)]);
        }
        return $res;
    }

    public function _redisGenerateByIds($ids)
    {
        $table = $this->redisTable;
        foreach ($ids as $v) {
            $key = $v;
            $this->redis->hdel($table, $key);
        }
    }

    public function overTime()
    {
        $time = strtotime(date('Y-m-d'));
        $where['end_time'] = ['<', $time];
        $data['status'] = 2;
        $this->_update($where, $data);
        $res = $this->redis->hkeys($this->redisTable);
        if (!empty($res)) {
            foreach ($res as $v) {
                $this->redis->hdel($this->redisTable, $v);
            }
        }
    }

    public function saveAccount()
    {
        $id = request('id');
        $shop = $this->_getOneById($id);
        if(!$shop){
            $this->error = '该店铺不存在';
            return false;
        }
        $data['username'] = request('username');
        $data['password'] = request('password');
        $data['old_password'] = request('old_password','');
        $data['confirm_password'] = request('confirm_password');

        if($data['old_password']) {
            if($data['old_password'] === $data['password']) {
                $this->error = '新密码不能与旧密码一致';
                return false;
            }
            if($shop['password'] != md5($data['old_password'])){
                $this->error = '原密码不正确';
                return false;
            }
        }
        if($shop['username']){
            $this->accountRule['username'] .= ','.$id.',id,admin_id,'.$shop['admin_id'];
        }

        $validator = $this->_validate($data,'accountRule','accountMsg');
        if (!$validator) {
            return false;
        }

        unset($data['old_password']);
        unset($data['confirm_password']);
        $data['password'] = md5($data['password']);
        $res = $this->_update(['id' => $id],$data);
        if(!$res) {
            $this->error = '保存失败';
            return false;
        }
        return $res;
    }

    public function login()
    {
        $username = request('username');
        $password = request('password');
        $where['username'] = $username;
        $shop = $this->_getOne($where);
        if (!$shop) {
            $this->error = '账号不存在！'; //应用级别禁用
            return false;
        }
        if (md5($password) !== $shop['password']) {
            $this->error = '账号或密码错误';
            return false;
        }
        $this->updateLogin($shop);
        $menu = new Menu();
        addSession('menus', $menu->getMenus('account'));
//        if($shop['end_time'] - (strtotime(date('Y-m-d')) + 3600*24*7)  < 0){
//            addSession('show_notice', 1);
//        }

        // 记录行为
        $actionLogModel = new ActionLog();
        $actionLogModel->action_log('shop_login', 'shop', $shop['id'], $shop['id']);
        return true;
    }

    protected function updateLogin($shop)
    {
        /* 记录登录SESSION和COOKIES */
        $auth = [
            'id' => $shop['id'],
            'admin_id' => $shop['admin_id'],
            'shop_id' => $shop['id'],
            'username' => $shop['username']
        ];
        session(['account' => $auth]);
        session(['account_sign' => data_auth_sign($auth)]);
        addSession('platIdentify','account'); // 设置平台标识
    }
}
